package net.barbierdereuille.android.AndroBib;

import net.barbierdereuille.android.AndroBib.AndroBib.BibTexColumn;
import net.barbierdereuille.android.AndroBib.AndroBib.GlobalColumn;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class EntryList extends ListActivity {
    private static final String TAG = "EntryList";
    
    private static final int LOAD_FILE = 1;

    private class FileChangeHandler extends AsyncQueryHandler {
    	public FileChangeHandler(ContentResolver cr) {
    		super(cr);
    	}

		@Override
		protected void onUpdateComplete(int token, Object cookie, int result) {
			super.onUpdateComplete(token, cookie, result);
			updateView();
			if(token == LOAD_FILE) {
				ProgressDialog dlg = (ProgressDialog)cookie;
				dlg.cancel();
				Log.d(TAG, "dialog closed");
			}
		}
    }

    private Cursor mCursor;
    //private DbLoader mDbLoader;
    private FileChangeHandler mHandler;
    
    public void updateView() {
    	Log.d(TAG, "updateView()");
		String[] proj = {BibTexColumn._ID, BibTexColumn.KEY};
		mCursor = getContentResolver().query(BibTexColumn.CONTENT_URI, proj, null, null, BibTexColumn.DEFAULT_SORT_ORDER);
		startManagingCursor(mCursor);
		String[] from = new String[] { BibTexColumn.KEY };
		int[] to = new int[] {R.id.entry_text };

		ListAdapter entries = new SimpleCursorAdapter(this, R.layout.entry_row, mCursor, from, to);
		setListAdapter(entries);
    }
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "Creating EntryList activity");
        setContentView(R.layout.entry_list);
        mHandler = new FileChangeHandler(getContentResolver());
        // Setup a progress dialog
        ProgressDialog dlg = ProgressDialog.show(EntryList.this, "", "Loading the bibtex file...", true);
        Log.d(TAG, "Starting working thread");
		ContentValues values = new ContentValues();
        // For now, use the /sdcard/bib/biblio.bib file
		values.put(GlobalColumn.FILE, "/sdcard/bib/biblio.bib");
		mHandler.startUpdate(LOAD_FILE, dlg, GlobalColumn.CONTENT_URI, values, null, null);
    }
    
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Cursor c = mCursor;
		c.moveToPosition(position);
		Intent i = new Intent(this, EntryViewActivity.class);
		i.putExtra(EntryViewActivity.REFERENCE, c.getLong(0));
		startActivity(i);
	}
	
}
